package com.xy.controller;

import com.xy.entity.Book;
import com.xy.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BookController {
    @Autowired
    BookService bookService;

    @Autowired
    StringRedisTemplate stringRedisTemp;


    @GetMapping("/findAll")
    @Cacheable(value = "books")
    public void findAll(){
        PageRequest pageable = PageRequest.of(2,3);
        Page<Book> page =bookService.getBookByPage(pageable);
        System.out.println("总页数:" + page.getTotalPages());
        System.out.println("总记录数:" + page.getTotalElements());
        System.out.println("查询结果" + page.getContent());
        System.out.println("当前页数" + page.getNumber());
        System.out.println("当前页记录数" + page.getNumberOfElements());
        System.out.println("每页记录数" + page.getSize());
    }

    @GetMapping("/getAll")
    @Cacheable(value = "books")
    public void FindAll(){
        List<Book> books = bookService.getAll();
        for (Book book : books) {
            System.out.println(book);
        }
    }

    @GetMapping("/getBookByIdAndAuthor/{id}/{author}")
    @Cacheable(value = "bs1")
    public void getBookByIdAndAuthor(@PathVariable("id") Integer id,@PathVariable("author") String author){
        System.out.println(id + author);
        List<Book> bs1 = bookService.getBookByIdAndAuthor(author,id);
        System.out.println(bs1);
    }
    @GetMapping("/search")

    public void search(){
        List<Book> bs1 = bookService.getBookByIdAndAuthor("颜笑道",9);
        List<Book> bs2 = bookService.getBooksByAuthorStartingWith("吴");
        List<Book> bs3 = bookService.getBooksByIdAndName("鼻",5);
        List<Book> bs4 = bookService.getBooksByPriceGreaterThan(35f);
        Book b = bookService.getMaxIdBook();
        System.out.println("bs1:" + bs1);
        System.out.println("bs2:" + bs2);
        System.out.println("bs3:" + bs3);
        System.out.println("bs4:" + bs4);
        System.out.println("b:" + b);
    }

    @GetMapping("/save")
    public void save(){
        Book book = new Book();
        book.setAuthor("颜笑道");
        book.setName("孝道");
        book.setPrice(500f);
        bookService.addBook(book);
    }

    @GetMapping("/test1")
    public void test1(){
        ValueOperations<String,String> ops1 = stringRedisTemp.opsForValue();
        ops1.set("name","骆驼祥子");
        System.out.println(ops1.get("name"));
    }
}
